
function fnAddEvent(){
	$(document).on('click','.register',function(){
		oDialogHandle.fnShowRegister();
	});
	$(document).on('click','.login',function(){
		oDialogHandle.fnShowLogin();
	});
	$(document).on('click','.logout',function(){
		fnLogout(fnIsLogin);
	});
	$('.videoUpload').on('click',function(){
		if(bIslogin){
			oDialogHandle.fnShowUpload();
		}else{
			alert('请先登录');
		}
	});

	$('.confirm').on('click',function(e){
		fnConfirm($(this));
	});
	$('.cancel').on('click',function(e){
		oDialogHandle.fnRemoveAll();
	});

	$('.recommand').on('click',function(){
		fnChangeList($(this));
	});
	$('.mine').on('click',function(){
		fnChangeList($(this));
	});
	$('.videoFavor').on('click',function(){
		var videoId = $('.jp-playlist-current').attr('data-videoid');
		console.log(videoId);
		fnCollect(videoId);
	});

	$(document).on('click','.scores',function(){
		fnScore($(this));
	});
}

function fnInitPlayerList(list){
	var myPlaylist = new jPlayerPlaylist(
		{
			jPlayer: ".playerWin",
			cssSelectorAncestor: ".player"
		}, 
		list,
		{
			ready:function(){
				for(var i = 0 ; i < oPlayList.length ; i++){
					$('.jp-playlist > ul > li').
					eq(i).
					attr('data-videoid',oPlayList[i].videoId).
					addClass('jp-playlists');
				//	console.log($('.jp-playlist > ul > li').eq(i));
				}
			},
			swfPath:'/static/js',
			supplied:'webmv,ogv,m4v',
			solution: "html",
			size:{
				width:'640px',
				height:'480px'
			},
			cssSelector:{
				play:'.play',
				pause:'.pause',
				stop:'.stop',
				duration:'.timeLength',
				currentTime:'.currTime',
				volumeBar:'.volumeBar',
				volumeBarValue:'.currVolume',
				playBar:'.currProc',
				seekBar:'.process'
			}
		}
	);
}
function fnInitUpload(){
	$('#fileUpload').fileupload({
        url:'/api/upload.php',
		dataType: 'json',
		/*
        formData:{
			method:'video',
			sort: '',
			description: ''
		},
		*/
		replaceFileInput: false,
        formData: function(form) {
			return [
				{
					name: 'method',
					value: 'video'
				}, {
					name: 'sort',
					value: $('.dialogUpload .sort').val()
				}, {
					name: 'description',
					value: $('.dialogUpload .description').val()
				}
			];
		},
        add:function(e , data){
        	$('.dialogUpload .confirm').on('click',function(){
        		var fileUpload = $('.dialogUpload #fileUpload').val();
				var sort = $('.dialogUpload .sort').val();
				var description = $('.dialogUpload .description').val();
				if(sort == '0'){
					alert('请选择分类');
				}else if(description == ''){
					alert('请为上传的文件添加描述')
				}else{
					data.submit();
				}
        	});
        },
        done: function (e, data) {
        	var response = data.response().jqXHR.responseJSON;
        	console.log(response);
        	if(response.status == 'success'){
        		fnSendVideoData(response.videoId);
        	}else{
        		if(response.message == 'upload failed'){
        			alert('上传失败');
        		}else if(response.message == 'this video has existed'){
        			alert('视频文件已存在，请选择其他文件');
        		}
        	}
        },
        progress: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#uploadProgress .uploadProgressBar').css('width',progress + '%');
        }
    });
}
var oDialogHandle={
	fnShowRegister:function(){
		$('.layer').addClass('show');
		$('.dialogRegister').addClass('show');
	},
	fnShowLogin:function(){
		$('.layer').addClass('show');
		$('.dialogLogin').addClass('show');
	},
	fnShowUpload:function(){
		$('.layer').addClass('show');
		$('.dialogUpload').addClass('show');
	},
	fnRemoveAll:function(){
		$('.show').removeClass('show');
		$('.listRec').addClass('show');
	}
}
function fnConfirm(target){
	if($(target).parent().hasClass('dialogRegister')){
		var userName = $(target).parent().find('.account').val();
		var password = $(target).parent().find('.password').val();
		if(userName != '' && password != ''){
			$.ajax({
				url:'/api/login.php',
				type:'post',
				dataType:'json',
				data:{
					method:'register',
					userName:userName,
					password:password
				},
				success:function(data){
					if(data == 'this userName has been used'){
						alert('该用户名已被使用，请更换其他名称');
					}else{
						oDialogHandle.fnRemoveAll();
						fnIsLogin();
					}
				}
			});
		}else{
			alert('用户名或密码不能为空！')
		}
	}else if($(target).parent().hasClass('dialogLogin')){
		var userName = $(target).parent().find('.account').val();
		var password = $(target).parent().find('.password').val();
		if(userName != '' && password != ''){
			$.ajax({
				url:'/api/login.php',
				type:'post',
				dataType:'json',
				data:{
					method:'login',
					userName:userName,
					password:password
				},
				success:function(data){
					if(data == 'fail to login'){
						alert('用户名或密码错误！');
					}else{
						oDialogHandle.fnRemoveAll();
						fnIsLogin();
					}
				}
			});
		}else{
			alert('用户名或密码不能为空！')
		}
	}else{}
}
function fnChangeList (target) {
	if($(target).hasClass('recommand')){
		$('.listRec').addClass('show');
		$('.listMine').removeClass('show');
		$(target).addClass('currList');
		$('.mine').removeClass('currList');
	}else{
		$('.listRec').removeClass('show');
		$('.listMine').addClass('show');
		$(target).addClass('currList');
		$('.recommand').removeClass('currList');
	}
}
function fnIsLogin(){
	$.ajax({
		url:'/api/login.php',
		type:'post',
		dataType:'json',
		data:{
			method:'isLogin'
		},
		success:function(data){
			console.log(data);
			var root = {list : data};
			if(data.status == 'login successfully'){
				bIslogin = true;
				var oRenderOption = {
					sTplId : 'tpl-personal',
					oData : root,
					sRenderType : 'html',
					oContainer : $('.header') 
				}
				fnRender(oRenderOption);
			}else{
				var oRenderOption = {
					sTplId : 'tpl-loginNav',
					oData : '',
					sRenderType : 'html',
					oContainer : $('.header')
				}
				fnRender(oRenderOption);
			}
		}
	});
}
function fnRender(oRenderOption){
	/*
		oRenderOption = {
			tplId,
			data,
			type(html or append),
			container
		}
	*/
	var sTplId = oRenderOption.sTplId,
		oData = oRenderOption.oData,
		oContainer = oRenderOption.oContainer,
		sRenderType = oRenderOption.sRenderType;

	var html = template.render(sTplId,oData);
	if(sRenderType == 'html'){
		oContainer.html(html);
	}else{
		oContainer.append(html);
	}
}
function fnLogout(callback){
	$.ajax({
		url:'/api/login.php',
		type:'post',
		dataType:'json',
		data:{
			method:'logout'
		},
		success:function(data){
			if(data == 'logout successfully'){
				bIslogin = false;
				callback();
			}
		}
	});
}
function fnSendVideoData(videoId){
	var sort = $('.dialogUpload .sort').val();
	var description = $('.dialogUpload .description').val();
	$.ajax({
		url:'/api/upload.php',
		type:'post',
		dataType:'json',
		data:{
			method:'formData',
			videoId:videoId,
			sort:sort,
			description:description
		},
		success:function(data){
		//	console.log(data);
			if(data.status == 'success'){
				alert('上传成功请到个人中心查看');
			}
		}
	});
}
function fnGetRec(){
	$.ajax({
		url:'/api/list.php',
		type:'post',
		dataType:'json',
		data:{
			method:'recommand'
		},
		success:function(data){
			var list = [];
			if(!data) data = [];
			for(var i = 0 ; i < data.length ; i++){
				list[i] = {
					title:data[i].videoName,
					artist:data[i].playSum,
					flv:"/static/" + data[i].videoPath,
					m4v:"/static/" + data[i].videoPath
				}
			}
			oPlayList = data;
		//	console.log(list);
			console.log(data);
			fnInitPlayerList(list);
			if(data && data.length > 0) currentVideoId = data[0].videoId;
			fnGetPlayingData(currentVideoId);
		}
	});
}
function fnGetPlayingData(videoId){
	console.log(videoId);
	$.ajax({
		url:'/api/list.php',
		type:'post',
		dataType:'json',
		data:{
			method:'current',
			videoId:videoId
		},
		success:function(data){
			console.log(data);
			fnRenderCurrentVideoData(data);
		}
	});
}
function fnCollect(videoId){
	$.ajax({
		url:'/api/list.php',
		type:'post',
		dataType:'json',
		data:{
			method:'collect',
			videoId:videoId
		},
		success:function(data){
		//	console.log(data);
			if(data.status == 'success'){
				fnGetPlayingData(currentVideoId);
			}else{
				alert('操作失败，请刷新重试');
			}
		}
	});
}
//点击播放时调用的方法
function fnRenderCurrentVideoData(data){
	console.log(data);
	$('.handleBar .videoTitle').html(data.videoName);
	$('.handleBar .videoFavor').html(data.isCollected?'已收藏/取消':'收藏');
	$('.handleBar .score').html(data.videoScore);
	if(data.isScored){
		$(document).off('mouseenter','.handleBar .videoScore');
		$(document).off('mouseleave','.handleBar .videoScore');

		$(document).on('mouseenter','.handleBar .videoScore',function(){
			$(this).find('.isScored').addClass('show');
		});
		$(document).on('mouseleave','.handleBar .videoScore',function(){
			$(this).find('.isScored').removeClass('show');
			
		});
	}else{
		$(document).off('mouseenter','.handleBar .videoScore');
		$(document).off('mouseleave','.handleBar .videoScore');

		$(document).on('mouseenter','.handleBar .videoScore',function(){
			$(this).find('.scorePanel').addClass('show');
		});
		$(document).on('mouseleave','.handleBar .videoScore',function(){
			$(this).find('.scorePanel').removeClass('show');
		});
	}
}
function fnScore(scores){
	var score = parseInt(scores.html());
//	console.log(score);
	$.ajax({
		url:'/api/list.php',
		type:'post',
		dataType:'json',
		data:{
			method:'score',
			score:score,
			videoId:currentVideoId
		},
		success:function(data){
			if(data.status =='success'){
				alert('操作成功');
				fnGetPlayingData(currentVideoId);
			}else{
				alert('操作失败，请刷新重试');
			}
		}
	})
}
function fnAddPlayTimes(currentVideoId){
	$.ajax({
		url:'/api/list.php',
		type:'post',
		dataType:'json',
		data:{
			method:'add',
			videoId:currentVideoId
		},
		success:function(data){

		}
	})
}